<template>
  <div class="compared-analyse-container">
    <div
      class="chart-wrapper"
      v-if="showLineChart"
    >
      <div class="edit-var-box color-primary">
        <i class="iconfont iconbianji"></i>
        <span @click="openVarBox">修改变量</span>
      </div>
      <div
        class="chart-box"
        id="comparedChart"
      ></div>
    </div>

    <div
      class="choose-var"
      v-if="!showLineChart"
    >
      <div
        class="choose-box"
        @click="openVarBox"
      >
        <van-icon name="plus" />
        <span class="color-gray">选择变量</span>
      </div>
    </div>

    <van-popup
      v-model="showVarBox"
      position="bottom"
      :close-on-click-overlay="false"
      :style="{ height: '64%' }"
    >
      <div class="var-box">
        <div class="var-box-header">
          <span class="model-name">{{ deviceName || '' }}</span>
          <p class="model-choose">已选择（<span class="color-primary">{{ chooseVarData.length }}</span>/5）</p>
        </div>
        <div class="var-search-box">
          <form action="/">
            <van-search
              v-model="searchKey"
              shape="round"
              placeholder="输入变量名称查找"
              clearable
              @search="handleSearch"
              @clear="handleClear"
            />
          </form>
        </div>
        <ul class="var-list scroll-box">
          <li
            v-for="item in filterVarList"
            :key="item.id"
            :class="{'color-primary': item.checked}"
            @click="selectVar(item)"
          >
            <span>{{ item.vname}}</span>
            <van-icon
              name="success"
              v-if="item.checked"
            />
          </li>
        </ul>
        <ul class="operate-box">
          <li @click="cancelSelect">取消</li>
          <li
            class="color-primary"
            @click="confirmSelect"
          >确定</li>
        </ul>
      </div>
    </van-popup>
  </div>
</template>

<script>
import dayjs from 'dayjs';
import * as echarts from 'echarts';
import { LineChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  DatasetComponentOption,
  TransformComponent
} from 'echarts/components';
// 标签自动布局，全局过渡动画等特性
import { LabelLayout, UniversalTransition } from 'echarts/features';
// 引入 Canvas 渲染器，注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from 'echarts/renderers';

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  LineChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer
]);

import { Popup, Search } from 'vant';
import { getModelVariable } from '@/api/deviceManage.js';
import dataObj from '../js/mockData.js';
import LineOptins from '../js/comparedLineChartOptions.js';

export default {
  name: 'ComparedAnalyse',
  components: {
    [Popup.name]: Popup,
    [Search.name]: Search
  },
  inject: ['parent'],
  props: {
    deviceCondition: {
      type: Object,
      required: true,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      showVarBox: false,
      searchKey: '',
      deviceVarData: [],
      socket: '',
      varTotal: 0,
      varList: [],
      filterVarList: [],
      deviceModelId: '',
      deviceName: '',
      chooseVarData: [],
      lineChart: '',
      lineData: [],
      index: 0,
      legendData: [],
      xAxisData: [],
      seriesData: [],
      showLineChart: false,
      showMaxLength: 200
    };
  },
  mounted() {
    // this.socket = this.parent.socket;
  },
  methods: {
    // 初始化第一个表
    initFirstChart() {
      if (this.index === 0) {
        this.lineChart = echarts.init(document.querySelector('#comparedChart'));
        this.lineData.map(item => {
          this.legendData.push(item.vname);

          this.seriesData.push({
            name: item.vname,
            type: 'line',
            data: []
          });
        });
      }
      this.xAxisData[this.index] = this.lineData[0].time || '';
      if (this.xAxisData.length > this.showMaxLength) {
        this.index = this.showMaxLength - 1;
        this.xAxisData.shift();
      }
      this.index++;
      this.seriesData.map((item, index) => {
        let val = this.lineData[index].val || 0;
        if (val === true || val === false) {
          val = val ? 1 : 0;
        }
        item.data.push(val);
        if (item.data.length > this.showMaxLength) {
          item.data.shift();
        }
      });
      LineOptins.legend.data = this.legendData;
      LineOptins.xAxis.data = this.xAxisData;
      LineOptins.series = this.seriesData;
      this.lineChart.setOption(LineOptins);
    },
    // 获取物模型变量
    getModelVariable() {
      getModelVariable({
        id: this.deviceCondition.deviceModelId
      }).then(res => {
        this.deviceVarData = res.data || [];
        if (res.data && res.data.length) {
          this.varList = res.data;
          this.varList.map(item => {
            item.checked = false;
          });
          this.filterVarList = JSON.parse(JSON.stringify(this.varList));
          if (this.chooseVarData.length) {
            this.chooseVarData.map(item => {
              this.filterVarList.map(ii => {
                if (ii.vname === item.vname) {
                  ii.checked = item.checked;
                }
              });
            });
          }
        }
      });
    },
    // websocket
    websocketFn() {
      const param = {
        device_id: this.deviceCondition.deviceValue,
        product_id: this.deviceCondition.deviceModelId,
        type: 2,
        is_single: true //是否单独监听此设备， 若为true 则客户端只会监听此设备
      };
      if (this.socket) {
        this.socket.send(JSON.stringify(param));
      } else {
        let token = localStorage.getItem('token');
        this.socket = new WebSocket(`ws://${location.host}/base/iot_websocket/ws/`, [token]);
        this.socket.onopen = res => {
          this.socket.send(JSON.stringify(param));
        };
      }

      this.socket.onmessage = res => {
        if (res.data) {
          const temp = [];
          const data = JSON.parse(res.data);
          const points = data.Record ? data.Record.Points : [];
          let time = data.Record ? data.Record.Time : '';
          time = time ? dayjs(time).format('HH:mm:ss') : '';
          this.deviceVarData.forEach(real => {
            points.forEach(item => {
              if (real.vk === item.K) {
                real.val = item.V;
                real.time = time;
              }
            });
            temp.push(real);
          });

          this.lineData = temp;
          this.initFirstChart();
        }
      };

      this.socket.onclose = res => {
        console.log('Connection closed.');
      };

      this.socket.onerror = () => {
        console.log('Connection error');
      };
    },
    // 打开选择变量
    openVarBox() {
      if (this.deviceCondition.deviceModelId) {
        this.deviceName = this.deviceCondition.deviceName || '';
        this.getModelVariable();
        this.showVarBox = true;
      } else {
        this.$toast('请先选择设备');
      }
    },
    // 搜索变量
    handleSearch() {
      let filterArr = this.varList.filter(item => {
        return item.vname.indexOf(this.searchKey) !== -1;
      });
      this.filterVarList = filterArr;
      if (this.chooseVarData.length) {
        this.chooseVarData.map(item => {
          this.filterVarList.map(ii => {
            if (ii.vname === item.vname) {
              ii.checked = item.checked;
            }
          });
        });
      }
    },
    // 清空搜索
    handleClear() {
      this.filterVarList = this.varList;
      if (this.chooseVarData.length) {
        this.chooseVarData.map(item => {
          this.filterVarList.map(ii => {
            if (ii.vname === item.vname) {
              ii.checked = item.checked;
            }
          });
        });
      }
    },
    // 选择变量
    selectVar(item) {
      if (!item.checked) {
        if (this.chooseVarData.length === 5) {
          this.$toast('最多选择5个变量');
          return;
        }
      }

      item.checked = !item.checked;
      this.$forceUpdate();
      if (item.checked) {
        this.chooseVarData.push(item);
      } else {
        this.chooseVarData.map((ii, idx) => {
          if (ii.vname === item.vname) {
            this.chooseVarData.splice(idx, 1);
          }
        });
      }
    },
    // 取消变量选择
    cancelSelect() {
      this.showVarBox = false;
    },
    // 确定变量选择
    confirmSelect() {
      if (this.chooseVarData.length) {
        this.showVarBox = false;
        this.deviceVarData = JSON.parse(JSON.stringify(this.chooseVarData));
        this.index = 0;
        this.legendData = [];
        this.xAxisData = [];
        this.seriesData = [];
        this.showLineChart = true;
        if (this.lineChart) {
          this.lineChart.clear();
        }
        this.websocketFn();
      } else {
        this.$toast('请选择变量');
      }
    }
  },
  beforeDestroy() {
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
  }
};
</script>

<style lang="scss" scoped>
.compared-analyse-container {
  .chart-wrapper {
    .edit-var-box {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding: 0.426667rem;
      font-size: 0.32rem;
      background-color: #fff;

      i {
        margin-right: 0.106667rem;
        font-size: 0.373333rem;
      }
    }
  }

  .chart-box {
    width: 100%;
    height: 8.906667rem;
    background-color: #fff;
  }

  .choose-var {
    display: flex;
    justify-content: center;
    width: 100%;
    padding: 0.426667rem 0;
    background-color: #fff;

    .choose-box {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 3.946667rem;
      height: 3.946667rem;
      border: 1px solid #dcdfe6;
      border-radius: 0.16rem;

      .van-icon {
        color: var(--color-gray);
        font-size: 0.853333rem;
      }

      span {
        margin-top: 0.48rem;
        font-size: 0.426667rem;
      }
    }
  }

  .van-popup--bottom {
    border-top-left-radius: 0.426667rem;
    border-top-right-radius: 0.426667rem;

    .var-box {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;

      .var-box-header {
        flex-shrink: 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 0.213333rem;
        padding: 0 0.426667rem;
        padding-top: 0.426667rem;

        .model-name {
          margin-right: 0.266667rem;
          font-size: 0.426667rem;
          line-height: 0.533333rem;
        }

        .model-choose {
          flex-shrink: 0;
          color: var(--color-deep-gary);
          font-size: 0.32rem;
        }
      }

      .var-search-box {
        flex-shrink: 0;
        margin-bottom: 0.213333rem;
        border-bottom: 1px solid var(--border-color);
      }

      .var-list {
        flex: 1;
        width: 100%;
        padding: 0 0.426667rem;

        li {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0.32rem 0;
          font-size: 0.373333rem;
          border-bottom: 1px solid var(--border-color);

          &:last-of-type {
            border-bottom: 0;
          }
        }
      }

      .operate-box {
        flex-shrink: 0;
        display: flex;
        width: 100%;
        height: 1.28rem;
        border-top: 1px solid var(--border-color);

        li {
          position: relative;
          display: flex;
          justify-content: center;
          align-items: center;
          width: 50%;
          font-size: 0.426667rem;

          &:first-of-type {
            &::after {
              content: '';
              position: absolute;
              top: 0;
              right: 0;
              width: 1px;
              height: 100%;
              background-color: var(--border-color);
            }
          }
        }
      }
    }
  }
}
</style>